define(function() {
	var ec = require('echarts');
	require('echarts/chart/line');
	require('echarts/chart/bar');
	var zrUtil = require('zrender/tool/util');
	var zrnumber = require('echarts/util/number');


	var option_hour = {
		title: {
			x: 'center',
			y: 'top'
		},
		grid: {
			x: '9%',
			y: '10%',
			x2: '4%'
		},
		tooltip: {
			trigger: 'axis'
				//formatter: '{b}min<br/>{a}:{c}'
		},
		calculable: true,
		xAxis: [{
			type: 'category',
			axisLabel: {
				interval: 6
					//formatter: '{value}min'
			},
			data: []
		}],
		yAxis: [{
			type: 'value'
		}],
		series: [{
			name: '',
			itemStyle: {
				normal: {
					color: '#C6E579'
				}
			},
			type: 'bar',
			stack: 'group',
			data: [],
			markPoint: {
				data: [{
					name: '自定义名字',
					symbolSize:20,
				}]
			}
		}]

	};
	var option_day = {
		title: {
			x: 'center',
			y: 'top'
		},
		grid: {
			x: '13%',
			y: '8%',
			x2: '0%'
		},
		tooltip: {
			trigger: 'axis',
			formatter: function(param) {
				var result = param[0][1] + '点<br/>';
				result += param[0][0] + ' : ' + zrnumber.addCommas(param[0][2]) + '<br/>';
				result += param[1][0] + ' : ' + zrnumber.addCommas(param[1][2]) + '<br/>';
				if (param[0].data && param[0].dataIndex - 1 >= 0) {
					var lasthour = param[0].series.data[param[0].dataIndex - 1];
					var s = (((param[0].data / lasthour) - 1) * 100).toFixed(2);
					result += '日环比 : ';
					if (s > 0) {
						result += '<span style="color: orangered">' + s + '%&#8593</span>';
					} else {
						result += '<span style="color: greenyellow">' + s + '%&#8595</span>';
					}
					result += '<br/>';
				}
				if (param[0].data && param[1].data) {
					var s2 = (((param[0].data / param[1].data) - 1) * 100).toFixed(2);
					result += '日同比 : ';
					if (s2 > 0) {
						result += '<span style="color: orangered">' + s2 + '%&#8593</span>';
					} else {
						result += '<span style="color: greenyellow">' + s2 + '%&#8595</span>';
					}
				}
				return result;
			}
		},
		calculable: true,
		xAxis: [{
			type: 'category',
			data: function() {
				var hour = [];
				for (var i = 0; i <= 23; i++) {
					hour[i] = i;
				}
				return hour;
			}()
		}],
		yAxis: [{
			type: 'value'
		}],
		legend: {
			data: ['今日数据', '昨日数据'],
			x: 'right'
		},
		series: [{
			name: '今日数据',
			type: 'line',
			data: []
		}, {
			name: '昨日数据',
			type: 'line',
			data: []
		}]
	};

	function RTChartHour(id, type) {
		this.id = id;
		this.type = type;
		this.option = zrUtil.clone(option_hour);
		this.myChart = ec.init(document.getElementById(id));
	}

	function getHoursKey(date) {
		var key;
		if (date.getMinutes() < 10) {
			key = date.getHours() + ':0' + date.getMinutes();
		} else {
			key = date.getHours() + ':' + date.getMinutes();
		}
		return key;
	}

	RTChartHour.prototype.getSeriesData = function(data) {
		if (!data) return [];
		var da = {};
		$.each(data, function(index, value) {
			var date = new Date(value.time);
			var key = getHoursKey(date);
			if (da[key]) {
				da[key] = Number((da[key] + value.value).toFixed(2));
			} else {
				da[key] = value.value;
			}
		});
		var x = [];
		var y = [];
		$.each(da, function(key, value) {
			x.push(key);
			y.push(value);
		});
		if (x.length > 60) {
			var i = x.length - 60;
			while (i--) {
				x.shift();
				y.shift();
			}
		}
		return {
			'x': x,
			'y': y
		};
		// return arr;
	}

	RTChartHour.prototype.init = function(bussline, platform) {
		var self = this;
		self.myChart.showLoading({
			text: '正在努力的读取数据中...'
		});
		$.ajax({
			url: '/dashboard/realtime/info/getHourData',
			type: 'POST',
			async: true,
			data: {
				"type": self.type,
				"bussline": bussline,
				"platform": platform
			},
			dataType: 'json',
			success: function(data) {
				if (data.data && data.data.length > 0) {
					self.lasttime = data.data[data.data.length - 1].time;
					self.option.title.text = title[self.type];
					self.option.series[0].name = title[self.type];
					self.option.series[0].itemStyle.normal.color = colorlist[self.type];
					var xy = self.getSeriesData(data.data);
					self.option.xAxis[0].data = xy.x;
					self.option.series[0].data = xy.y;
					//self.option.series[0].data=self.getSeriesData(data.data);
				};
				self.myChart.setOption(self.option);
				self.myChart.hideLoading();

				clearInterval(timeTicket);
				var timeTicket = setInterval(function() {
					flush(self)
				}, 1 * 1000);

				function flush(obj) {
					$.ajax({
						url: '/dashboard/realtime/info/getHourData',
						type: 'POST',
						async: false,
						data: {
							"type": self.type,
							"bussline": bussline,
							"platform": platform,
							"time": obj.lasttime
						},
						dataType: 'json',
						success: function(data) {
							if (!data.data || data.data.length == 0) return;
							obj.lasttime = data.data[data.data.length - 1].time;
							//obj.counter+=data.data.length;
							//缓存360个最新数据
							$.each(data.data, function(index, value) {
								var date = new Date(value.time);
								var key = getHoursKey(date);
								var x = self.option.xAxis[0].data;
								var y = self.option.series[0].data;
								if (key == x[x.length - 1]) {
									y[y.length - 1] = Number((y[y.length - 1] + value.value).toFixed(2));
									self.option.series[0].markPoint.data[0].xAxis=x.length - 1;
									self.option.series[0].markPoint.data[0].yAxis=y[y.length - 1]; 
									self.option.series[0].markPoint.data[0].value=y[y.length - 1]; 
									self.myChart.setOption(self.option);
								} else {
									self.myChart.delMarkPoint(0,'自定义名字');
									x.shift();
									y.shift();
									x.push(key);
									y.push(value.value);
									self.myChart.addData([
										[
											0, // 系列索引
											y[y.length - 1], // 新增数据
											false, // 新增数据是否从队列头部插入
											false, // 是否增加队列长度，false则自定删除原有数据，队头插入删队尾，队尾插入删队头
											x[x.length - 1]
										]
									]);
									var mk= zrUtil.clone(option_hour.series[0].markPoint);
									mk.data[0].xAxis=x.length - 1;
									mk.data[0].yAxis=y[y.length - 1];
									mk.data[0].value=y[y.length - 1]; 
									self.myChart.addMarkPoint(0,mk);
								}

							});
						}
					});
				}
			},
			timeout: 5000,
			error: function() {
				self.myChart.hideLoading();
			}
		});
	}

	function RTChartDay(id, type) {
		this.id = id;
		this.type = type;
		this.lasttime = 0;
		this.option = zrUtil.clone(option_day);
		this.myChart = ec.init(document.getElementById(id));
	}

	RTChartDay.prototype.init = function(bussline, platform) {
		var self = this;
		self.myChart.showLoading({
			text: '正在努力的读取数据中...'
		});

		function update(data) {
			self.data = data.data;
			if (data.data && data.data.length > 0) {
				//self.lasttime=data.data[data.data.length-1].time;
				var ss = [],
					ss2 = [];
				$.each(data.data, function(index, value) {
					ss.push(value.value);
				});
				self.option.series[0].data = ss;
			}
			if (data.yesdata) {
				$.each(data.yesdata, function(index, value) {
					ss2.push(value.value);
				});
				self.option.series[1].data = ss2;
			}
			self.myChart.setOption(self.option, true);
		}
		$.ajax({
			url: '/dashboard/realtime/info/getDayData',
			type: 'POST',
			async: true,
			data: {
				"type": self.type,
				"bussline": bussline,
				"platform": platform
			},
			dataType: 'json',
			success: function(data) {
				self.option.title.text = title[self.type];
				update(data);
				self.myChart.hideLoading();
				clearInterval(timeTicket);
				var timeTicket = setInterval(function() {
					flush(self)
				}, 5 * 60 * 1000);

				function flush(obj) {
					$.ajax({
						url: '/dashboard/realtime/info/getDayData',
						type: 'POST',
						async: true,
						data: {
							"type": self.type,
							"bussline": bussline,
							"platform": platform
						},
						dataType: 'json',
						success: function(data) {
							console.log('getDayData:');
							console.log(data)
							update(data);
						}
					});
				}
			},
			timeout: 5000,
			error: function() {
				self.myChart.hideLoading();
			}
		});
	}

	var title = {
		infoNum: '新增信息量'
	}

	var colorlist = {
		infoNum: '#C1232B',
		// vppv: '#B5C334',
		// listpv: '#FCCE10',
		// uv: '#9BCA63',
	}

	function start(bussline, platform) {
		$('#new').html(zrnumber.addCommas($('#new').html()));
		clearInterval(timeTicket);
		var timeTicket = setInterval(function() {
			flushCash()
		}, 3 * 1000);
		/**
		 *
		 */
		function flushCash() {
			$.ajax({
				url: '/dashboard/realtime/info/getNew',
				type: 'POST',
				async: true,
				data: {
					"bussline": bussline,
					"platform": platform
				},
				dataType: 'json',
				success: function(data) {
					$('#new').html(zrnumber.addCommas(data.value));
				},
				timeout: 5000
			});
		}

		var crt_pv_day = new RTChartDay('pv_day', 'infoNum');
		var crt_pv_hour = new RTChartHour('pv_hour', 'infoNum');
		crt_pv_day.init(bussline, platform);
		crt_pv_hour.init(bussline, platform);

		// var crt_vppv_day = new RTChartDay('vppv_day', 'vppv');
		// var crt_vppv_hour = new RTChartHour('vppv_hour', 'vppv');
		// crt_vppv_day.init(bussline, platform);
		// crt_vppv_hour.init(bussline, platform);

		// var crt_listpv_day = new RTChartDay('listpv_day', 'listpv');
		// var crt_listpv_hour = new RTChartHour('listpv_hour', 'listpv');
		// crt_listpv_day.init(bussline, platform);
		// crt_listpv_hour.init(bussline, platform);

		//         var crt_uv_day = new RTChartDay('uv_day','uv');
		// var crt_uv_hour =new RTChartHour('uv_hour','uv');
		// crt_uv_day.init(bussline,platform);
		// crt_uv_hour.init(bussline,platform);

	}

	return {
		'start': start
	};
});